package org.lc.kcjxzj.textcheck;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.hankcs.hanlp.dictionary.CoreSynonymDictionary;

/**
 * NLP配置和工具类
 */
public class NlpConfig {
    
    // 同义词相似度缓存
    private static final Map<String, Double> synonymWeightCache = new ConcurrentHashMap<>();
    
    /**
     * 判断两个词是否为同义词
     */
    public static boolean areSynonyms(String word1, String word2) {
        if (word1 == null || word2 == null || word1.isEmpty() || word2.isEmpty()) {
            return false;
        }
        
        // 相同词直接返回true
        if (word1.equals(word2)) {
            return true;
        }
        
        // 使用HanLP的同义词词典计算相似度
        try {
            long distance = CoreSynonymDictionary.distance(word1, word2);
            return distance <= 10; // 距离小于等于10认为是同义词
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取两个词的同义词权重
     * 返回值范围：[0.0, 1.0]
     * 1.0 表示完全相同
     * 0.0 表示完全无关
     */
    public static double getSynonymWeight(String word1, String word2) {
        if (word1 == null || word2 == null || word1.isEmpty() || word2.isEmpty()) {
            return 0.0;
        }

        // 相同词返回1.0
        if (word1.equals(word2)) {
            return 1.0;
        }

        // 生成缓存key
        String cacheKey = word1.compareTo(word2) < 0 
            ? word1 + "|" + word2
            : word2 + "|" + word1;

        // 从缓存中获取
        return synonymWeightCache.computeIfAbsent(cacheKey, k -> {
            try {
                // 使用HanLP的同义词词典计算相似度
                long distance = CoreSynonymDictionary.distance(word1, word2);
                
                // 将距离转换为权重
                if (distance == Long.MAX_VALUE) {
                    return 0.0;
                }
                
                // 距离越大，权重越小
                double weight = 1.0 - (Math.min(distance, 100) / 100.0);
                
                // 对权重进行调整，使其符合实际需求
                if (distance <= 5) {
                    weight = 0.9; // 非常相似
                } else if (distance <= 10) {
                    weight = 0.8; // 较为相似
                } else if (distance <= 20) {
                    weight = 0.6; // 稍有关联
                } else if (distance <= 50) {
                    weight = 0.4; // 关联较弱
                } else {
                    weight = 0.2; // 关联很弱
                }
                
                return weight;
            } catch (Exception e) {
                return 0.0;
            }
        });
    }

    /**
     * 清理同义词权重缓存
     */
    public static void clearSynonymWeightCache() {
        synonymWeightCache.clear();
    }

    /**
     * 获取缓存大小
     */
    public static int getCacheSize() {
        return synonymWeightCache.size();
    }
}